package com.orangelife.mobile.lookRepair.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.PhoneCallUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.lookRepair.entity.LookRepairBean;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.thirdlib.timeline.TimelineAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LookForRepairDetailActivity extends OrangeLifeBaseActivity {
	
	/**用户下单*/
	private TextView tvUserOrder;
	/**师傅抢单*/
	private TextView tvMasterGrabSingle;
	/**上门查看*/
	private TextView tvDoorLook;
	/**估价开工*/
	private TextView tvAppraisalStarts;
	/**定价验收*/
	private TextView tvPricingAcceptance;
	/**订单编号*/
	private TextView tvOrderNumber;
	/**订单编号旁边的状态*/
	private TextView tvOrderStatus;
	/**维修人员名字*/
	private TextView tvMasterName;
	/**维修人员电话*/
	private TextView tvMasterPhone;
	/**打电话按钮*/
	private ImageButton ibCall;
	/**地址*/
	private TextView tvAddress;
	/**报修问题*/
	private LinearLayout llRepairProblem;
	/**取消订单按钮*/
	private Button btnCancelOrder;
	/**标题中间*/
	private TextView tvTitle;
	/**标题右边*/
	private TextView tvTitleRight;
	/**接收从listview传过来的数据*/
	private Map<String,Object> map;
	/**接收从后台传来的数据*/
	private Map<String,Object> mapDetail;
	private Dialog dialog;
	/** 时间轴  */
	private List<Map<String,Object>> listTimeLine = new ArrayList<Map<String,Object>>();
	/**维修单子状态*/
	private int statChild;
	/**对话框中的内容*/
	private String dialogMessage;
	/** 时间轴*/
	private ListView slvList;
	/** 估价单是否付款 */
//	private int isPay;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lookrepair_detail);
		initeView();
		findView();
	}
	
	/**
	 * 初始化
	 */
	private void initeView(){
		tvTitle = (TextView)findViewById(R.id.tv_title);
		tvTitleRight = (TextView)findViewById(R.id.tv_title_right);
		tvUserOrder = (TextView)findViewById(R.id.tvUserOrder);
		tvMasterGrabSingle = (TextView)findViewById(R.id.tvMasterGrabSingle);
		tvDoorLook = (TextView)findViewById(R.id.tvDoorLook);
		tvAppraisalStarts = (TextView)findViewById(R.id.tvAppraisalStarts);
		tvPricingAcceptance = (TextView)findViewById(R.id.tvPricingAcceptance);
		tvOrderNumber = (TextView)findViewById(R.id.tvOrderNumber);
		tvOrderStatus = (TextView)findViewById(R.id.tvOrderStatus);
		tvMasterName = (TextView)findViewById(R.id.tvMasterName);
		tvMasterPhone = (TextView)findViewById(R.id.tvMasterPhone);
		ibCall = (ImageButton)findViewById(R.id.ibCall);
		tvAddress = (TextView)findViewById(R.id.tvAddress);
		llRepairProblem = (LinearLayout)findViewById(R.id.llRepairProblem);
		btnCancelOrder = (Button)findViewById(R.id.btnCancelOrder);
		slvList = (ListView)findViewById(R.id.slvList);
	}
	
	
	private void findView(){
		tvTitle.setText(R.string.order_detail);
		tvTitleRight.setVisibility(View.INVISIBLE);
		llRepairProblem.setOnClickListener(listener);
		btnCancelOrder.setOnClickListener(listener);
		ibCall.setOnClickListener(listener);
		slvList.setOnItemClickListener(itemListener);
		Intent intent = getIntent();
		map = (Map<String, Object>) intent.getSerializableExtra("detail");
		dialog = DialogHelper.getInstance().createLoadingDialog(
				LookForRepairDetailActivity.this, Constant.LOADING);
		dialog.show();
		if(map != null){
		if("0".equals(map.get("userReaded").toString())){
			setRead();
		}
		}else{
			setRead();
		}
		getRepairDetail();
	}
	
	/**
	 * 点击item监听器
	 */
	
	private OnItemClickListener itemListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if(position == 0){
				Intent intent = new Intent();
				intent.putExtra("repairCode", mapDetail.get("repaireCode").toString());
				intent.setClass(LookForRepairDetailActivity.this, PlaceOrderDetailActivity.class);
				startActivity(intent);
			}
		}
	};
	
	/**
	 * 监听器
	 */
	private OnClickListener listener = new OnClickListener() {
		
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.llRepairProblem:
				if(mapDetail != null){
					String repairID =  mapDetail.get("invcID").toString();
					Intent intent = new Intent();
					intent.putExtra("lookDetail", 0);
					intent.putExtra("followID", repairID);
					intent.setClass(LookForRepairDetailActivity.this, RepairProblemActivity.class);
					startActivity(intent);
				}
				break;
			case R.id.btnCancelOrder:
				if(mapDetail != null){
					if(statChild<2 || statChild == 8 || statChild == 9){
						dialogMessage = getResources().getString(R.string.sure_cancel_order);

					}else if(statChild == 3 || statChild == 2){
							dialogMessage = getResources().getString(R.string.sure_cancel_order1);
						
					}else if(statChild > 3 && statChild < 7){
						dialogMessage = getResources().getString(R.string.sure_cancel_order2);
					}
					isOrderDialog();
				}
				break;
			case R.id.ibCall:
				if(mapDetail!=null){
					String phone = mapDetail.get("linkmanTel").toString();
					PhoneCallUtil.getInstances().callPhone(LookForRepairDetailActivity.this,phone, "是否拨打此电话号码？");
				}
				break;
			default:
				break;
			}
		}
	};
	
	/**
	 * 弹出对话框
	 */
	private void isOrderDialog() {
		final ConfirmDialog dialog = new ConfirmDialog(LookForRepairDetailActivity.this, "温馨提示",dialogMessage, "返回", "取消订单");
		dialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
			@Override
			public void doLeft() {
				dialog.dismiss();
			}

			@Override
			public void doRight() {
				dialog.dismiss();
				//取消订单
				cancelOrder();
				return;
			}
		});

		dialog.show();
	}
	private void isOrderDialog1() {
		AlertDialog.Builder builder = new Builder(LookForRepairDetailActivity.this);
		builder.setMessage(dialogMessage);
		builder.setPositiveButton("取消订单", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				//取消订单
				cancelOrder();
				return;
			}
		});
		builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}
	
	/**
	 * 设置详情
	 */
	private void setDetail() {
		String stat = mapDetail.get("newestFollowStat").toString();
		if("1".equals(stat)){
			tvUserOrder.setBackgroundResource(R.drawable.progress_orange_big);
		}else if("2".equals(stat)){
			tvMasterGrabSingle.setBackgroundResource(R.drawable.progress_orange_big);
		}else if("3".equals(stat)){
			tvDoorLook.setBackgroundResource(R.drawable.progress_orange_big);
		}else if("4".equals(stat)){
			tvAppraisalStarts.setBackgroundResource(R.drawable.progress_orange_big);
		}else if("5".equals(stat)){
			tvPricingAcceptance.setBackgroundResource(R.drawable.progress_orange_big);
		}
		tvOrderNumber.setText(mapDetail.get("repaireCode").toString());
		statChild = Integer.parseInt( mapDetail.get("repaireSubStatus").toString());
		if(statChild == 1){
			tvOrderStatus.setText("待上门");
		}else if(statChild == 2){
			tvOrderStatus.setText("待估价");
		}else if(statChild == 3){
			tvOrderStatus.setText("待确认估价");
			btnCancelOrder.setVisibility(View.GONE);
		}else if(statChild == 4){
			tvOrderStatus.setText("跟进中");
		}else if(statChild == 5){
			tvOrderStatus.setText("待定价");
			btnCancelOrder.setVisibility(View.GONE);
		}else if(statChild == 6){
			tvOrderStatus.setText("待确认定价");
			btnCancelOrder.setVisibility(View.GONE);
		}else if(statChild == 7){
			tvOrderStatus.setText("待取消订单");
			btnCancelOrder.setVisibility(View.GONE);
		}else if(statChild == 8){
			tvOrderStatus.setText("已验收");
			btnCancelOrder.setVisibility(View.GONE);
		}else if(statChild == 9){
			tvOrderStatus.setText("待保修");
			btnCancelOrder.setVisibility(View.GONE);
		}else if(statChild == 10){
			tvOrderStatus.setText("已结单");
			tvOrderStatus.setTextColor(getResources().getColor(R.color.lightGray));
			btnCancelOrder.setVisibility(View.GONE);
		}else if(statChild == 11){
			tvOrderStatus.setText("已取消");
			tvOrderStatus.setTextColor(getResources().getColor(R.color.lightGray));
			btnCancelOrder.setVisibility(View.GONE);
		}
		String memberID = mapDetail.get("repairemanID").toString();
		String invcRepaireID = mapDetail.get("invcRepaireID").toString();
		String invcID = mapDetail.get("invcID").toString();
		String repairCode = mapDetail.get("repaireCode").toString();
		if(StringUtil.isBlank(memberID)){
			tvOrderStatus.setText("待抢单");
		}
		tvMasterName.setText(mapDetail.get("linkmanName").toString());
		tvMasterPhone.setText(mapDetail.get("linkmanTel").toString());
		tvAddress.setText(mapDetail.get("address").toString());
		listTimeLine = (List<Map<String, Object>>) mapDetail.get("pageEntity");
		TimelineAdapter adapter = new TimelineAdapter(this, listTimeLine,invcRepaireID,repairCode);
		slvList.setAdapter(adapter);
		setListViewHeightBasedOnChildren(slvList);
		adapter.notifyDataSetChanged();
	}
	
	/**
	 * 设置listview高度
	 * @param listView
	 */
	private void setListViewHeightBasedOnChildren(ListView listView) {   
        // 获取ListView对应的Adapter   
		TimelineAdapter listAdapter = (TimelineAdapter) listView.getAdapter();   
        if (listAdapter == null) {   
            return;   
        }   
   
        int totalHeight = 0;   
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {   
            // listAdapter.getCount()返回数据项的数目   
            View listItem = listAdapter.getView(i, null, listView);   
            // 计算子项View 的宽高   
            listItem.measure(0, 0);    
            // 统计所有子项的总高度   
            totalHeight += listItem.getMeasuredHeight();    
        }   
   
        ViewGroup.LayoutParams params = listView.getLayoutParams();   
        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));   
        // listView.getDividerHeight()获取子项间分隔符占用的高度   
        // params.height最后得到整个ListView完整显示需要的高度   
        listView.setLayoutParams(params);   
    }
	
	
	/**
	 * 设置用户已读
	 */
	private void setRead(){
		String repairID = "";
		if(map != null){
			repairID = map.get("invcRepaireID").toString();
		}else{
			Intent intent = getIntent();
			repairID = intent.getStringExtra("jumpuri");
		}
		Map<String, Object> mapSubmit = new HashMap<String, Object>();
		mapSubmit.put("invcRepaireID", repairID);

		JSONRequest.getInstance().sendRequest(JSONRequest.PUT, Constant.URL_READED, mapSubmit, handler, 6, HttpUtil.ACTION_JSON);
		
	}
	
	/**
	 * 获得详情
	 * 
	 */
	private void getRepairDetail() {
		String repairID = "";
		if(map != null){
			repairID = map.get("invcRepaireID").toString();
		}else{
			Intent intent = getIntent();
			repairID = intent.getStringExtra("jumpuri");
			if(StringUtil.isBlank(repairID)){
				repairID = intent.getStringExtra("id");
				if(StringUtil.isBlank(repairID)){
					repairID = LookRepairBean.getInvcRepaireID();
				}
			}
		}
		Map<String, Object> mapSubmit = new HashMap<String, Object>();
		mapSubmit.put("{invcRepaireID}", repairID);
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put("map", mapSubmit);
		rootMap.put("url", Constant.URL_LOOKREAPIR_DETAIL);
		rootMap.put("wat", 9);
		new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
	}
	/**
	 * 取消订单
	 * 
	 */
	private void cancelOrder() {
		dialog.show();
		String repairID = "";
		String repairSub = "";
		repairSub = mapDetail.get("repaireSubStatus").toString();
		if(mapDetail != null){
			List<Map<String,Object>> listPage =  (List<Map<String, Object>>) mapDetail.get("pageEntity");
			repairID = listPage.get(0).get("invcID").toString();
		}else{
			Intent intent = getIntent();
			repairID = intent.getStringExtra("jumpuri");
		}
		Map<String, Object> mapSubmit = new HashMap<String, Object>();
		mapSubmit.put("invoiceID", repairID);
		mapSubmit.put("repaireSubStatus", repairSub);
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put("map", mapSubmit);
		rootMap.put("url", Constant.URL_CANCEL_ORDER);
		rootMap.put("wat", 7);
		new JSONRequest(JSONRequest.PUT, rootMap, handler, HttpUtil.ACTION_JSON);
	}
	
	/**
	 * 处理返回的信息数据
	 */
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 9:
				mapDetail = new HashMap<String, Object>();

				mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
						msg.obj.toString()).get("entity");
				DialogHelper.closeDialog(dialog);
				setDetail();
				break;
			case 7:
				String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
				.get("errInfo").toString();
				if (errInfo.equals("OK")){
					DialogHelper.closeDialog(dialog);
					ToastHelper.getInstance()._toast(getResources().getString(R.string.cancel_success));
					IntentHelper.getInstances().getIntent(LookForRepairDetailActivity.this, LookForRepairListActivity.class);
				    finish();
				    ExitApplication.getInstance().finishPaidActivity();
				}else{
					DialogHelper.closeDialog(dialog);
					ToastHelper.getInstance()._toast(
							getResources().getString(
									R.string.cancel_fail));
				}
				break;
			case 6:
				errInfo = JSONHelper.jsonToMap(msg.obj.toString())
				.get("errInfo").toString();
				if (errInfo.equals("OK")){
//					DialogHelper.closeDialog(dialog);
				}else{
//					DialogHelper.closeDialog(dialog);
				}
				break;
			case 1011:
				isLogin(dialog);
				break;
			case 500:
				DialogHelper.closeDialog(dialog);
				ToastHelper.getInstance()._toast(
						msg.obj.toString());
				break;
			case 15001:
				DialogHelper.closeDialog(dialog);
				ToastHelper.getInstance()._toast(
						msg.obj.toString());
				break;
			default:
				break;
			}
		}

	};


}
